<template>
	<view class="select-printer-page">
		<u-loading-page :loading="pageLoading"></u-loading-page>
		<div v-show="!pageLoading">
			<view class="title">请选择默认打印设备</view>
			<u-radio-group v-model="printId" shape="square" placement="column">
				<u-radio v-for="item in printList" :label="item.printerDes" :name="item.id" :value="item.id" :key="item.id"></u-radio>
			</u-radio-group>
			<button class="uni-btn" type="primary" :loading="loading" @click="submitPrintSetting">确 认</button>
		</div>
	</view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';
import { http } from '@/utils/http';
import { useUserStore } from '@/stores/useUserStore';

// 获取默认打印设备，储存打印设备Object
const defaultPrinter = computed(() => (useUserStore().defaultPrinter ? JSON.parse(useUserStore().defaultPrinter) : ''));

// 打印设备id
const printId = ref('');

// 打印设备list
const printList = ref();

/**
 * 获取打印设备列表
 */
const pageLoading = ref(false);
async function getPrintList() {
	try {
		pageLoading.value = true;
		const result: PageResult<any> = await http({
			method: 'POST',
			url: '/system/sysPrinterSetting/getList',
			data: {}
		});
		pageLoading.value = false;
		printList.value = result.data || [];
		//如果printId匹配不上，则重置store中的默认打印设备
		if (printId.value) {
			const length = printList.value?.filter((e) => e.id === printId.value).length;
			if (!length) {
				useUserStore().setDefaultPrinter('');
			}
		}
	} catch (e) {
		console.log(e);
		pageLoading.value = false;
	}
}

/**
 * 提交打印设备信息
 */
const loading = ref(false);
function submitPrintSetting() {
	if (!printList.value?.length || !printId.value) {
		uni.showToast({
			title: '请选择打印设备',
			icon: 'error'
		});
		return false;
	} else {
		const current = printList.value?.filter((item) => item.id === printId.value)[0] || '';
		loading.value = true;
		useUserStore().setDefaultPrinter(current);
		setTimeout(() => {
			loading.value = false;
			uni.showToast({
				title: '设置成功'
			});
		}, 500);
	}
}

onShow(() => {
	if (defaultPrinter.value) {
		const { id } = defaultPrinter.value;
		printId.value = id;
	}
	getPrintList();
});
</script>

<style lang="scss" scoped>
.select-printer-page {
	padding: $uni-page-padding;
	padding-top: 10px;
	padding-bottom: 50px;
	.title {
		padding: 10px 0 10px;
		font-weight: bold;
		font-size: 15px;
		color: #16254e;
	}
	.u-radio {
		margin: 8px 0;
	}
	:deep(.u-radio__text) {
		color: #16254e !important;
		line-height: 20px !important;
	}
	:deep(.u-radio__icon-wrap) {
		margin-right: 10px;
	}

	.uni-btn {
		margin-top: 40px;
		border-radius: 0px;
		height: 46px;
		line-height: 46px;
		font-size: 16px;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
	}
}
</style>
